/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.database.bean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author diego
 */
@ManagedBean
@SessionScoped
public class CargaArchivoBean {

    /**
     * Creates a new instance of CargaArchivoBean
     */
    private String destination = "C:\\Users\\diego\\Documents\\NetBeansProjects\\trunk\\CRI\\web\\resources\\archivos\\";
    private String nombre;
    private UploadedFile file;  
    
    
   public void upload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Perfecto ! ", event.getFile().getFileName() + "El archivo ha sido cargado.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        // Do what you want with the file.
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
            nombre=event.getFile().getFileName();
            System.err.println(nombre);
        } catch (IOException e) {
            e.printStackTrace();
        }



    }

    public void copyFile(String fileName, InputStream in) {
        try {
            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(destination + fileName));
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            in.close();
            out.flush();
            out.close();

            // System.out.println("New file created!");
        } catch (IOException e) {
            //  System.err.println(e.getMessage());
        }
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
    
    public UploadedFile getFile() {  
        return file;  
    }  
   
    public void setFile(UploadedFile file) {  
        this.file = file;  
    }  
    
    
}
